/*
 * ﻿Copyright (C) 2012 NewMain Softech
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package com.newmainsoftech.ant;

import org.apache.tools.ant.Project;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Helper class for test by routing ant log call during tests.
 * 
 * @author <a href="mailto:artymt@gmail.com">Arata Y.</a>
 */
@Aspect
public abstract class AbstractAspectForRoutingAntLog {
	Logger logger = LoggerFactory.getLogger( this.getClass());
		Logger getLogger() {
			return logger;
		}
		
	void routeAntLog( String msg, int antLogLevel) {
		Logger logger = getLogger();
		
		switch( antLogLevel) {
		case Project.MSG_DEBUG:
		case Project.MSG_VERBOSE:
			if ( logger.isDebugEnabled()) {
				logger.debug( msg);
			}
			break;
		case Project.MSG_INFO:
			if ( logger.isInfoEnabled()) {
				logger.info( msg);
			}
			break;
		case Project.MSG_WARN:
			if ( logger.isWarnEnabled()) {
				logger.warn( msg);
			}
			break;
		case Project.MSG_ERR:
			if ( logger.isErrorEnabled()) {
				logger.error( msg);
			}
			break;
		}
	}
	
	@Pointcut
	public abstract void pointcutWithinAntUtilClasses();

	@AfterReturning( value="pointcutWithinAntUtilClasses() " 
			+ "&& (call( void org.apache.tools.ant.Task.log( java.lang.String, int)) " 
					+ "|| call( void org.apache.tools.ant.Task.log( java.lang.String)))")
	public void afterReturningAdvisedCallToAntLog( JoinPoint joinPoint) {
		Object[] args = joinPoint.getArgs();
			String msg = (String)args[ 0];
			int antLogLevel = Project.MSG_INFO;
				if ( args.length > 1) {
					antLogLevel = (Integer)args[ 1];
				}
			routeAntLog( msg, antLogLevel);
	}
}
